const base = require("./../../base");

module.exports = class extends base {
    async _initialize() {
        await super.isWxaAuth();
        await super.isShopAuth();
        await super.isUserAuth();
    }

    /**
     *
     * @api {get} /shop/api/shop/product/product/info 商品详情
     * @apiDescription 商品详情
     * @apiGroup Shop/api
     * @apiVersion 0.0.1
     *
     * @apiHeader {String} Referer 小程序referer.
     *
     * @apiParam {Number} id   商品id
     *
     * @apiSampleRequest /shop/api/shop/product/product/info
     *
     */
    async info() {
        const { id } = this.query;
        const shopId = this.state.shop.id;
        const wxaId = this.state.wxa.id;
        const userId = this.state.user.id;
        if (!id) {
            this.fail("参数错误");
            return;
        }
        console.log("shopId", shopId);
        console.log("wxaId", wxaId);
        console.log("userId", userId);
        const product = await this.model("product")
            .query(qb => {
                qb.where("id", id);
                qb.where("shop_id", shopId);
            })
            .fetch({
                withRelated: [
                    "album",
                    "sku",
                    "group.group",
                    "collection",
                    {
                        collection: qb => {
                            qb.where("collection_type", "shop_product");
                            qb.where("user_id", userId);
                            qb.where("shop_id", shopId);
                            qb.where("collection_id", id);
                        }
                    }
                ]
            });
        console.log("product", product);
        let skuData = [];
        if (product && product.sku.length) {
            let skuIds = [];
            if (product.sku.length) {
                for (const item of product.sku) {
                    skuIds = skuIds.concat(
                        item.sku_ids.split(","),
                        item.sku_pids.split(",")
                    );
                }
            }
            const sku = await this.model("shop_sku")
                .query(qb => {
                    qb.whereIn("id", skuIds);
                })
                .fetchAll();
            skuData = this.getTree(sku, "pid", "child");
        }
        if (wxaId && userId && id) {
            this.hook.run("productAnalysis", wxaId, userId, id);
        }
        this.success(Object.assign(product, { skuData }));
    }
};
